package cn.xuqiudong.demo.generate.deferred;

import cn.xuqiudong.common.base.model.BaseResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述:
 * @author Vic.xu
 * @since 2023-03-17 10:41
 */
@RestController
@RequestMapping("/deferred")
public class DeferredResultController {

    @GetMapping("/test")
    public DeferredResult<BaseResponse<?>> test(){
        //超时时间
        long timeoutValue = 5000L;
        Map<String, Object> data = new HashMap<>();
        long start = System.currentTimeMillis();
        data.put("startTime:", LocalTime.now());
        data.put("msg", "超时了");

        DeferredResult<BaseResponse<?>> result = new DeferredResult(timeoutValue,BaseResponse.success(data));
        new Thread(()->{
            try {
                Thread.sleep(3000);
                data.put("endTime:", LocalTime.now());
                data.put("intervel", geInterval(start));
                data.put("msg", "success");
                result.setResult(BaseResponse.success(data));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }).start();
        return result;
    }

    private static long geInterval(long start){
        return System.currentTimeMillis() - start;
    }
}
